<?php

namespace app\common\model;

use think\Model;

/**
 * 基础模型类 Model
 * @author kaige
 * @copyright ©2022 泉州市盛筑信息科技有限公司 版权所有
 */
class Base extends Model
{
    /**
     * 默认分页条数
     */
    public const PAGELIMIT = 20;

    /**
     * 根据主键获取一条记录
     * @return array
     */
    public function _one($id = 0)
    {
        $info = self::find($id);
        if ($info) {
            $info = $info->toArray();
        }
        return $info;
    }

    /**
     * 获取一个字段值
     * @return array | null
     */
    public function _onefield($id = 0, $field = '')
    {
        if (empty($id)) return '';
        $info = self::find($id);
        if ($info) {
            $info = $info->toArray();
        }
        return $info[$field];
    }

    /**
     * 删除数据，支持批量删除
     * @param string $id 
     * @return array
     */
    public function _del($id)
    {
        if (!empty($id)) {
            //批量删除
            $ids = explode(',', $id);
            $info = $this->find($ids[0])->toArray();
            if (in_array("delete_time", $info, true)) {
                //如果delete_time存在，软删除
                $this->where(['id' => $ids])->useSoftDelete('delete_time', time())->delete();
                return _ok('软删除成功!');
            }
            //否则根据主键物理删除
            self::destroy($ids);
            return _ok('删除成功!');
        }
        return _err('删除失败!');
    }

    /**
     * 单字段值更新
     * @param $key,$val,$id
     * @return array
     */
    public function _field($key, $val, $id)
    {
        if (!empty($key) && !empty($id)) {
            $info = $this->find($id);
            if (!empty($info)) {
                $array = array_keys($info->toArray());
                if (in_array($key, $array)) {
                    $info[$key] = $val;
                    $info->save();
                    return _ok('修改成功!');
                }
            }
        }
        return _err('修改失败!');
    }

    /**
     * 公用列表数据，默认分页
     *
     * @param array $data
     * @param boolean $isPage
     * @return array
     */
    public function _list($data, $isPage = true)
    {
        $objwith = [];
        $arraywhere = [
            'where' => [],
            'whereOr' => [],
            'field' => "*",
            'order' => [],
        ];
        if (method_exists($this, '_with')) {
            $objwith = $this->_with();
        }
        if (method_exists($this, '_where')) {
            $arraywhere = $this->_where($data);
            if (isset($arraywhere['whereOr'])) {
                if (empty($arraywhere['whereOr'])) {
                    $arraywhere['whereOr'] = [];
                }
            } else {
                $arraywhere['whereOr'] = [];
            }
        }

        if ($isPage) {
            if (isset($data['limit'])) {
                $limit = $data['limit'];
            } else {
                $limit = self::PAGELIMIT;
            }
            if (empty($objwith)) {
                $list = $this->field($arraywhere['field'])->where($arraywhere['where'])->whereOr($arraywhere['whereOr'])->order($arraywhere['order'])->paginate($limit);
            } else {
                $list = $this->with($objwith)->field($arraywhere['field'])->where($arraywhere['where'])->whereOr($arraywhere['whereOr'])->order($arraywhere['order'])->paginate($limit);
            }

            $count = $list->total();
            if (!empty($list)) $list = $list->getCollection();
        } else {
            if (empty($objwith)) {
                $list = $this->field($arraywhere['field'])->where($arraywhere['where'])->whereOr($arraywhere['whereOr'])->order($arraywhere['order'])->select();
            } else {
                $list = $this->with($objwith)->field($arraywhere['field'])->where($arraywhere['where'])->whereOr($arraywhere['whereOr'])->order($arraywhere['order'])->select();
            }
            $count = count($list);
            if (!empty($list)) $list = $list->toArray();
        }
        //是否控制关联子表的字段部分显示
        if (method_exists($this, '_visible')) {
            $arrayfield = $this->_visible();
            if (!empty($list)) $list = $list->visible($arrayfield);
        }
        //是否格式化数据
        if (method_exists($this, '_format')) {
            if (!empty($list)) $list = $this->_format($list);
        }

        //非标准layui表格，可能需要增加其它项目数据给前端
        if (method_exists($this, 'layuiAddItem')) {
            return $this->layuiAddItem($data, $count, $list);
        }
        return _layui($count, $list);
    }

    /**
     * 保存表单数据
     * @param $data
     * @return array
     */
    public function saveForm($data)
    {
        if (empty($data)) {
            return  _err('缺少参数');
        }
        if (isset($data['id']) && !empty($data['id'])) {
            $bmodel = $this->where('id', $data['id'])->find();
            $result = $bmodel->save($data);
            if ($result) {
                return _ok('编辑成功');
            }
        } else {
            $result = self::create($data);
            if ($result) {
                $return =  _ok('添加成功');
                if (!empty($result->id)) {
                    $return['data'] = $result->id;
                }
                return $return;
            }
        }
        return _err('操作失败');
    }

    /**
     * 根据默认查询字段查询
     * @param $name
     * @param bool $where
     * @return mixed
     */
    public function getInfoWhere($where = true, $field = ['*'])
    {
        return $this->field($field)->where($where)->find();
    }
}
